package com.enterpriseDigitalPlatform.util;

import jakarta.servlet.http.HttpServletRequest;

import java.util.Arrays;
import java.util.Objects;

public class IpUtil {
    // todo 获取客户端真实ip
    public static String getIpAddr(HttpServletRequest request) {
        Objects.requireNonNull(request, "HttpServletRequest must not be null");
        String ip = Arrays.stream(new String[]{"x-forwarded-for", "Proxy-Client-IP", "WL-Proxy-Client-IP", "HTTP_X_FORWARDED_FOR", "x-real-ip"})
                .map(request::getHeader)
                .filter(header -> header != null && !"unknown".equalsIgnoreCase(header.trim()))
                .findFirst()
                .orElse(request.getRemoteAddr());
        // 处理 x-forwarded-for 中可能存在的多个IP，取第一个非unknown的有效IP
        if ("x-forwarded-for".equalsIgnoreCase(ip)) {
            String[] ips = ip.split(",");
            for (String ipPart : ips) {
                if (!"unknown".equalsIgnoreCase(ipPart.trim())) {
                    return ipPart.trim();
                }
            }
        }
        return ip.isEmpty() ? "unknown" : ip.trim();
    }
}
